package operation;

import car.Vehicle;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBHelper {
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/pta_experiment?characterEncoding=utf8&useSSL=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "111111";

    // 私有化构造方法，避免外部直接创建实例
    private DBHelper() {
    }

    // 获取数据库连接
    public static Connection getConnection() {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl(URL);
        ((MysqlDataSource) dataSource).setUser(USERNAME);
        ((MysqlDataSource) dataSource).setPassword(PASSWORD);

        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("Error getting database connection", e);
        }
    }


    public static void insertVehicle(Vehicle vehicle) {
        try (Connection connection = DBHelper.getConnection()) {
            String sql = "INSERT INTO vehicle (vehicleId, brand, type, perRent) VALUES (?, ?, ?, ?)";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, vehicle.getVehicleId());
                statement.setString(2, vehicle.getBrand());
                statement.setString(3, vehicle.getType());
                statement.setInt(4, vehicle.getPerRent());
                statement.executeUpdate();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void deleteVehicle(String vehicleId) {
        try (Connection connection = DBHelper.getConnection()) {
            String sql = "DELETE FROM vehicle WHERE vehicleId = ?";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, vehicleId);
                statement.executeUpdate();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeConnection(Connection connection) {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

